package com.jprocms.module.cms.controller.directive;

import com.jprocms.module.cms.controller.admin.content.vo.ContentSideReqVO;
import com.jprocms.module.cms.dal.dataobject.content.ContentDO;
import com.jprocms.module.cms.service.content.ContentService;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.Map;

/**
 * 内容上下篇 自定义标签
 *
 * @author jprocms
 */
public class ContentSideDirective implements TemplateDirectiveModel {
    /**
     * 内容ID
     */
    private static final String ID = "id";
    /**
     * 内容所在栏目ID
     */
    private static final String CHANNEL_ID = "channelId";
    /**
     * 发布日期。
     */
    public static final String RELEASE_DATE = "releaseTime";
    /**
     * 置顶级别。
     */
    public static final String TOP_LEVEL = "topLevel";
    /**
     * 是否下一篇
     */
    private static final String NEXT = "next";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);

        Long id = Directives.getLongRequired(params, ID);
        Long channelId = Directives.getLongRequired(params, CHANNEL_ID);
        boolean findNext = Directives.getBoolean(params, NEXT, true);
        OffsetDateTime offsetDateTime = Directives.getOffsetDateTime(params, RELEASE_DATE);
        Integer topLevel = Directives.getIntegerRequired(params, TOP_LEVEL);
        ContentDO contentDO = contentService.findSide(new ContentSideReqVO(id, channelId, offsetDateTime, topLevel), findNext);
        loopVars[0] = env.getObjectWrapper().wrap(contentDO);
        body.render(env.getOut());
    }

    private final ContentService contentService;

    public ContentSideDirective(ContentService contentService) {
        this.contentService = contentService;
    }
}
